package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.bean.Dialogue;
import com.kang.bean.Users;
import com.kang.mapper.DialogueMapper;
import com.kang.service.DialogueService;
import com.kang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: photo_fawu
 * @description:
 * @author: K.faWu
 * @create: 2021-11-23 17:18
 **/
@Service
public class DialogueServiceImpl extends ServiceImpl<DialogueMapper, Dialogue> implements DialogueService {

    @Autowired
    private DialogueMapper dialogueMapper;
    @Autowired
    private UserService userService;

    @Override
    public void saveDialogue(Long fromUserId, Long toUserId, String msg, int msgType, int type, int isRead) {
        Dialogue dialogue = new Dialogue();
        dialogue.setDialogueId(fromUserId.toString()+toUserId);
        dialogue.setFromUserId(fromUserId);
        dialogue.setToUserId(toUserId);
        dialogue.setMsg(msg);
        dialogue.setMsgType(msgType);
        dialogue.setType(type);
        dialogue.setIsRead(isRead);
        dialogueMapper.insert(dialogue);
    }

    @Override
    public List<Dialogue> getNotReadDialogue(Long fromUserId, Long toUserId) {
        QueryWrapper<Dialogue> wrapper = new QueryWrapper<>();
        wrapper.in("dialogue_id", fromUserId.toString()+ toUserId, toUserId.toString()+fromUserId);
        wrapper.eq("from_user_id", fromUserId);
        wrapper.eq("is_read", 1);
        return dialogueMapper.selectList(wrapper);
    }

    @Override
    public void saveRead(List<Dialogue> list) {
        list.forEach(dialogue -> {
            dialogue.setIsRead(0);
            dialogueMapper.updateById(dialogue);
        });
    }

    @Override
    public List<Dialogue> getHistorIcalNews(Long toUserId, HttpServletRequest request) {
        Users users = userService.getUsers(request.getHeader("token"));
        QueryWrapper<Dialogue> wrapper = new QueryWrapper<>();
        wrapper.in("dialogue_id", users.getId().toString()+ toUserId, toUserId.toString()+users.getId());
        return dialogueMapper.selectList(wrapper);
    }
}
